﻿using AutoMapper;
using ZGL.Api.Data;
using ZGL.Api.Entity;
using ZGL.Api.Models.dto;
using ZGL.Api.Models.vo;

namespace ZGL.Api.Services.Menu
{
    public class MenuService : IMenuService
    {
        public readonly DataContext DataContext;
        public readonly IMapper Mapper;
        public MenuService(DataContext dataContext, IMapper _mapper)
        {
            DataContext = dataContext;
            Mapper = _mapper;
        }

        public void addMenu(MenuAddDto menu)
        {
            var sysMenu = Mapper.Map<SysMenuAuthority>(menu);
            DataContext.SysMenuAuthorities.Add(sysMenu);
            DataContext.SaveChanges();
        }

        public int delMenu(long id)
        {
            var menu=DataContext.SysMenuAuthorities.Find(id);
            if (menu!=null) {
                DataContext.SysMenuAuthorities.Remove(menu);
                DataContext.SaveChanges();
            }
            else
            {
                throw new Exception("无此菜单");
            }
            return 1;
        }

        public SysMenuAuthorityVo getMenu(long id)
        {
            var menu = DataContext.SysMenuAuthorities.Find(id);
            var sysMenu = Mapper.Map<SysMenuAuthorityVo>(menu);
            return sysMenu;
        }

        public Dictionary<string, object> getMenuList(MenuDto menuDto)
        {
            IQueryable<SysMenuAuthority> list = null;
            int total = 0;
            Dictionary<string, object> Dictionary = new Dictionary<string, object>();
            if (!string.IsNullOrEmpty(menuDto.MenuName))
            {
                //list = from s in DataContext.SysUsers where s.Username.Contains(userDto.Username) orderby s.UserId select s;
                list = DataContext.SysMenuAuthorities.Where(r => r.MenuName.Contains(menuDto.MenuName)).OrderBy(r => r.CreateTime);
            }
            else
            {
                list = DataContext.SysMenuAuthorities.OrderBy(r => r.CreateTime);
            }
            List<SysMenuAuthority> items = new List<SysMenuAuthority>();
            items = list.Skip((menuDto.current - 1) * menuDto.size).Take(menuDto.size).ToList();
            total = list.Count();
            Dictionary.Add("list", items);
            Dictionary.Add("total", total);
            return Dictionary;
        }

        public void putMenu(MenuPutDto menu)
        {
            var Menu=DataContext.SysMenuAuthorities.Find(menu.MenuAuthId);
            if (Menu==null)
            {
                throw new Exception("无此菜单");
            }
            var sysMenu = Mapper.Map<SysMenuAuthority>(menu);
            DataContext.SysMenuAuthorities.Update(sysMenu);
            DataContext.SaveChanges();
        }
    }
}
